// pages/trajectory.js
const app = getApp();
const util = require('../../../utils/util');
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //日期选择框
    showDate:false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },  
    //统计到几天前
    dayNum:14,
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //传参memberId
    memberId:null,
    //传参-查询日期
    oneDaysAgo:util.timeFormatDay(new Date()),
    //当前阈值
    threshold:0,
    //修改阈值
    showThreshold:false,
    //输入阈值
    thresholdVal:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let currentUser = app.globalData.userInfo;
    
    if(currentUser){
      if(options && options.memberId){
        this.setData({ 
          memberId: options.memberId,
          oneDaysAgo: options.oneDaysAgo
        })
      }else{
        this.setData({ 
          memberId: currentUser.depart
        })
      }

      //查询阈值
      this.getThreshold();

      //设置统计几天数据
      this.getBeforeDate();

      //获取异常数据
      this.getList();

    }else{
      wx.redirectTo({
        url: "/pages/login/login?errorData="+'1'
      })
    }  
  },

  //获取异常数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    }); 
    
    let parameter={
      "memberId":this.data.memberId,
      "oneDaysAgo":this.data.oneDaysAgo,
      page: {
        page: this.data.page,
        pageSize: 10
      }
    }  
    
    CommonService.findErrorDataListGo(parameter).then(res=>{
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;

        result.forEach(item => {
          let start=new Date((item.locusStartTime).replaceAll("-","/"));
          let end=new Date((item.endTime).replaceAll("-","/"));
          let long=(end-start)/1000;
          if(long>0){
            long=util.secondToFormat(long);
            item.long=long;
          } 
        });
        
        console.log('异常数据列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result)
        })
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      }) 
    })    
  },

  //作废异常数据
  deleteData(item){
    this.setData({ 
      showDelete: true,
      dataItem:item.currentTarget.dataset.detail
		})
  },

  confirmDelete(){
    let obj = this.data.dataItem;
    
    let parameter ={
      "imei":obj.imei,
      "startTime":util.timeFormatTZ(obj.locusStartTime),
      "endTime":util.timeFormatTZ(obj.endTime)      
    }
    CommonService.deleteErrorDataListGo(parameter).then(res=>{
      if (res.data.success == true){
        Toast.success('已删除');
        //刷新列表和页码
        this.refreshListAndPage();
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.clear();         
    })
  },  

  //设置可选的最小日期
  getBeforeDate(){
    let rusult=util.countPrevDay(new Date(),this.data.dayNum);
    this.setData({ 
			minDate: rusult
		})  
  },

  //显示日期选择框
  onShowDate(){
    this.setData({ 
			showDate: true
		})
  },

  //关闭日期选择框
  onCloseDate(){
    this.setData({ 
			showDate: false
		})
  },

  //确定日期时
  onConfirmDate(event){
    let currentDate=event.detail;
    this.setData({
      currentDate: currentDate,
      oneDaysAgo: util.timeFormatDay(currentDate)
    })

    //关闭日期选择框
    this.onCloseDate();

    //刷新列表和页码
    this.refreshListAndPage();
  }, 
  
  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //查询阈值
  getThreshold(){
    let param={
      memberId:app.globalData.userInfo.depart
    }

    CommonService.getThreshold(param).then(res=>{
      if(res.data.data && res.data.data.result){
        this.setData({
          threshold: res.data.data.result
        })
      }
    }).catch((error) => {             
    })
  }, 

  //显示修改阈值
  onShowThreshold(){
    this.setData({
      showThreshold: true,
      thresholdVal: this.data.threshold
    })   
  },

  //隐藏修改阈值
  onCloseThreshold(){
    this.setData({
      showThreshold: false
    })
  },

  //获取输入的阈值
  onChangeThreshold(e){
    this.setData({ 
      thresholdVal: e.detail.value
    })   
  },

  //确认阈值
  onConfirmThreshold(){
    let val=this.data.thresholdVal;
    if(/^[1-9]\d*$/.test(val)){
      if(val>=60){
        //修改阈值
        this.setThreshold(val);
        this.onCloseThreshold();        
      }else{
        Toast.fail('不能低于60');
      }
    }else{
      Toast.fail('请输入整数');
    }  
  },

  //修改阈值
  setThreshold(val){
    let param={
      memberId: app.globalData.userInfo.depart,
      minute: parseInt(val) 
    }

    CommonService.setThreshold(param).then(res=>{
      if(res.statusCode==200){
        Toast.success('修改成功');
        this.getThreshold();
      }
    }).catch((error) => {             
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})